from flask import (
    Blueprint, json
)
from blemesh import db, util, dbmanager
from .mesh import login_request
from .error import error_handle

light = db.Light()
dm = dbmanager.dbmanagement()

bp = Blueprint('con', __name__, url_prefix='/con')

@bp.route('/con_list/',methods=['POST'])
@error_handle
@login_request
def con_list(user_id, req, res):
    m_id = req['meshid']
    type = req['type']
    sql = "select * from controller where m_id = "+str(m_id)+";"
    res['cons'] = []
    result = dm.query(sql)
    if result:
        for item in result:
            item["uuid"] = item["ios_uuid"] if type=="ios" else item["android_uuid"]
        res['cons'] = result
    return json.dumps(res)

@bp.route('/get_group_of_con/',methods=['POST'])
@error_handle
@login_request
def get_group_of_con(user_id, req, res):
    c_id = req['c_id']
    res['groups'] = []
    sql = "select * from con_group join MeshDB.group on g_id = id where c_id = "+str(c_id)+";"
    result = dm.query(sql)
    if result:
        res['groups'] = result
    return json.dumps(res)

@bp.route('/add_con_into_mesh/',methods=['POST'])
@error_handle
@login_request
def add_con_into_mesh(user_id, req, res):
     name = req['name']
     m_id = req['m_id']
     address = req['address']
     uuid = req['uuid']
     devicekey = req['devicekey']
     sql = "insert into controller(name,address, uuid,devicekey,m_id) values('"+name+"','"+address+"','"+uuid+"','"+devicekey+"',"+str(m_id)+");"
     dm.update(sql)
     return json.dumps(res)

@bp.route('/delete_con_of_mesh/', methods=['POST'])
@error_handle
@login_request
def delete_con_of_mesh(user_id, req, res):
    c_id = req['c_id']
    sql = "delete from controller where c_id = "+str(c_id)+";"
    dm.update(sql)
    return json.dumps(res)

@bp.route('/config_con/', methods=['POST'])
@error_handle
@login_request
def config_con(user_id, req, res):
    c_id = req['c_id']
    sql = "delete from con_group where c_id = "+str(c_id)+";"
    dm.update(sql)
    groupidlist = req['groupidlist']
    print("groupidlist!!!!!!!!!!!!!!!!!!!!",groupidlist)
    for groupid in groupidlist:
        sql = "insert into con_group(c_id,g_id) values("+str(c_id)+","+str(groupid)+");"
        dm.update(sql)
    return json.dumps(res)

@bp.route('/rename_con/', methods=['POST'])
@error_handle
@login_request
def rename_con(user_id, req, res):
    c_id = req['c_id']
    name = req['name']
    sql="update controller set name = '"+name+"' where c_id  = "+str(c_id)+";"
    dm.update(sql)
    return json.dumps(res)
